package com.atguigu.bigdata.chapter07.window;

import com.atguigu.bigdata.bean.WaterSensor;
import com.atguigu.bigdata.util.AtguiguUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

/**
 * @Author lzc
 * @Date 2022/9/4 8:28
 */
public class Flink01_Window_Tumble {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                }
            })
            .keyBy(WaterSensor::getId)
            // 定义一个长度为5s的窗口
//            .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            // 定义一个长度为5, 滑动步长为2窗口
            .window(SlidingProcessingTimeWindows.of(Time.seconds(5), Time.seconds(2)))
//            .window(ProcessingTimeSessionWindows.withGap(Time.seconds(3)))
            // 窗口处理函数
            .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
            
                // 处理窗口中元素的方法: 当窗口关闭的时候执行一次
                @Override
                public void process(String key,  // 属于哪个key的窗口
                                    Context ctx,  // 上下文对象, 可以获取到窗口信息
                                    Iterable<WaterSensor> elements, // 窗口触发计算的时候, 存储着窗口内所有的元素
                                    Collector<String> out) throws Exception {
                    ArrayList<WaterSensor> list = new ArrayList<>();
                    // Iterable很多操作不能做, 比如排序, 一般是把他转成一个List集合再操作
                    for (WaterSensor ws : elements) {
                        list.add(ws);
                    }
                
                    // 获取窗口的开始时间
                    String stt = AtguiguUtil.toDatTime(ctx.window().getStart());
                    // 获取窗口的结束时间
                    String edt = AtguiguUtil.toDatTime(ctx.window().getEnd());
                
                    out.collect(key + " " + stt + " " + edt + "  " + list);
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*

滚动窗口:

5000, 0,
new TumblingProcessingTimeWindows(size.toMilliseconds(), 0, WindowStagger.ALIGNED)

this.size = size = 5000
this.globalOffset = offset = 0


// 返回值: 某个元素所在的所有窗口
public Collection<TimeWindow> assignWindows(
        Object element, long timestamp, WindowAssignerContext context) {
    final long now = context.getCurrentProcessingTime();
    if (staggerOffset == null) {
        staggerOffset =
                windowStagger.getStaggerOffset(context.getCurrentProcessingTime(), size);
    }
    long start =
            TimeWindow.getWindowStartWithOffset(
                    now, (globalOffset + staggerOffset) % size, size);
    return Collections.singletonList(new TimeWindow(start, start + size));
}

// 窗口的开始时间
long start = TimeWindow.getWindowStartWithOffset(
                            now, (globalOffset + staggerOffset) % size, size);
                            
    // 因为是滚动窗口, 所以, 返回的集合中只有一个窗口
    return Collections.singletonList(new TimeWindow(start, start + size));
    
    参数1: 系统时间
    参数2: 0
    参数3: 5000
    
    TimeWindow.getWindowStartWithOffset(now, (globalOffset + staggerOffset) % size, size);
         public static long getWindowStartWithOffset(long timestamp, long offset, long windowSize) {
            return timestamp - (timestamp - offset + windowSize) % windowSize;
            return timestamp - (timestamp + 5000) % 50000
                     6700 - (6700 + 5000) % 5000
                     6700 - 1700 = 5000  // 时间戳 - 时间%5000
        }
        
        
-------------------
滑动

// List集合存储的是这个元素所在的所有窗口
List<TimeWindow> windows = new ArrayList<>((int) (size / slide));
// 计算最后一个窗口的开始时间
时间, 0, 2000
long lastStart = TimeWindow.getWindowStartWithOffset(timestamp, offset, slide);

// 找到所有窗口
for (long start = lastStart; start > timestamp - size; start -= slide) {
    windows.add(new TimeWindow(start, start + size));
}
return windows;
 
 */